package com.ericsson.enap.modules.kpi.task.vgc;

import com.ericsson.common.domain.CollectBizTypeEnum;
import com.ericsson.common.domain.NetTypeEnum;
import com.ericsson.common.quartz.task.ManualTask;
import com.ericsson.common.util.*;
import com.ericsson.enap.modules.kpi.entity.EnipFormula;
import com.ericsson.enap.modules.kpi.entity.EnipFormulaChild;
import com.ericsson.enap.modules.kpi.entity.VgcFifKpi;
import com.ericsson.enap.modules.kpi.service.EnipKpiAlarmService;
import com.ericsson.enap.modules.kpi.service.IEnipFormulaChildService;
import com.ericsson.enap.modules.kpi.service.IEnipFormulaService;
import com.ericsson.enap.modules.kpi.service.VgcFifKpiService;
import com.ericsson.enap.modules.kpi.thread.VgcChfFivKpiDataProcessThread;
import com.ericsson.enap.modules.sys.entity.EpcDict;
import com.ericsson.enap.modules.sys.service.EpcDictService;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * VGCChF5分钟指标处理
 */
@Component
public class VgcChfFIVKpiTask implements ManualTask {
    private Logger log = LoggerUtils.Logger(LogFileName.VgcFivKpiJob);

    @Autowired
    private VgcFifKpiService vgcFivKpiService;
    @Autowired
    private IEnipFormulaService enipFormulaService;
    @Autowired
    private IEnipFormulaChildService enipFormulaChildService;
    @Autowired
    private EpcDictService epcDictService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisCache redisCache;
    private static final String nettype="enip_base_netelement_type";
    @Autowired
    private EnipKpiAlarmService enipKpiAlarmService;
    @Value("${collectorIp}")
    private String collectorIp;

    @Override
    public void execute() {
       Date now = new Date();
        //删除过期数据
       deleteMongodbData(now);
       List<VgcFifKpi> vgcFivKpis= vgcFivKpiService.findVgcFifKpiList(collectorIp, Integer.parseInt(CollectBizTypeEnum.VGCCmdKpi.value()), Integer.parseInt(NetTypeEnum.CHF.value()));
        EnipFormula enipFormulaQuery=new EnipFormula();
        enipFormulaQuery.setBizType(Integer.parseInt(CollectBizTypeEnum.VGCCmdKpi.value()));
        enipFormulaQuery.setNetType(NetTypeEnum.CHF.value());
       List<EnipFormula> enipFormulas= enipFormulaService.selectEnipFormulaList(enipFormulaQuery);
        Map<String,String> netTypeNameMap= getNetMap();
        String storePath=downloadBasePath();
        List<EnipFormulaChild> enipFormulaChildList=enipFormulaChildService.selectEnipFormulaChildList();
        Map<String,String> enipFormulaChildMap=enipFormulaChildList.stream().collect(Collectors.toMap(enipFormulaChild -> {return enipFormulaChild.getNetId().toString()+"_"+enipFormulaChild.getFormulaId().toString();}, EnipFormulaChild::getFormula));
       for(VgcFifKpi vgcFivKpi: vgcFivKpis) {
           //解析公式对应的Expression
           List<EnipFormula> formulaList=analysisFormulaExpression(enipFormulas,enipFormulaChildMap,vgcFivKpi);
           VgcChfFivKpiDataProcessThread vgcChfFivKpiDataProcessThread=new VgcChfFivKpiDataProcessThread(enipKpiAlarmService,redisCache,vgcFivKpi, netTypeNameMap.get(vgcFivKpi.getType().toString()), formulaList, now, log,storePath);
           new Thread(vgcChfFivKpiDataProcessThread).start();
       }
    }

    private Map<String, String> getNetMap() {
        Map<String,String> netMap=new HashMap<>();
        netMap.put("5","CHFFIVE");
        return netMap;
    }

    /**
     * 删除过期数据
     * @param now
     */
    private void deleteMongodbData(Date now){
        EpcDict epcDict=new EpcDict();
        epcDict.setKeyName("VGCKPIMONGODBTIME");
        epcDict= epcDictService.selectEpcDict(epcDict);
        if(null!=epcDict&&!"".equals(epcDict.getKeyValue())) {
            String deleteTime = DateUtils.getStatisTime(Integer.parseInt(epcDict.getKeyValue())*1440+30,now,"yyyy-MM-dd HH:mm:00");
            log.info("deleteTime-------------------------------:"+deleteTime);
            Query query = Query.query(Criteria.where("dateTime").lte(deleteTime));
            mongoTemplate.remove(query,"vgckpi_16_chf");
        }
    }

    /**
     * 获取下载文件存储的基础目录
     * @return
     */
    private String downloadBasePath(){
        EpcDict epcDict=new EpcDict();
        epcDict.setKeyName("VGCFIVKPISTOREPATH");
        epcDict= epcDictService.selectEpcDict(epcDict);
        if(null!=epcDict&&!"".equals(epcDict.getKeyValue())) {
            return epcDict.getKeyValue();
        }else{
            return "/opt";
        }
    }

    private List<EnipFormula> analysisFormulaExpression(List<EnipFormula> formulaList,Map<String,String> enipFormulaChildMap, VgcFifKpi vgcFifKpi){
        List<EnipFormula> formulaListTemp=new ArrayList<>();
        for (Iterator iter = formulaList.iterator(); iter.hasNext(); ) {
            EnipFormula f = (EnipFormula)((EnipFormula) iter.next()).clone();
            if(enipFormulaChildMap.size()>0&&enipFormulaChildMap.containsKey(vgcFifKpi.getId().toString()+"_"+f.getId())) {
                f.setFormula(enipFormulaChildMap.get(vgcFifKpi.getId().toString()+"_"+f.getId()));
                String formulaText = FormulaConvert.convertFormula(f.getFormula());
                try {
                    Expression compiledExp = AviatorEvaluator.compile(formulaText);
                    f.setExpression(compiledExp);
                    formulaListTemp.add(f);
                } catch (Exception e) {
                    iter.remove();
                    log.error("error====" + e.getMessage() + "====", e);
                } finally {
                    continue;
                }
            }
        }
        return formulaListTemp;
    }
}
